import React, {PureComponent, Fragment} from 'react';
import {findDOMNode} from 'react-dom';
import moment from 'moment';
import {connect} from 'dva';
import {List, Card, Row, Radio, Input, Badge, Button, Icon, Dropdown, Menu, Avatar, Modal, Form, message, Select, Table, Popconfirm,DatePicker,Tag
} from 'antd';
import MyPagination from '@/components/MyPagination';
import DetailInfo from './Info'
import debounce from 'lodash/debounce'
import {ellipsis,download} from '@/utils/utils';
import ExportForm from './ExportForm'
import config from '../../../config/config'
import BuildModalTitle from '@/components/BuildModalTitle';
const FormItem = Form.Item;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;
const SelectOption = Select.Option;
const {Search, TextArea} = Input;
@connect(({withdrawals, loading}) => ({
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      banks:[]
    };
  }



  componentDidMount() {
    this.changeTableY()
    const {dispatch} = this.props;
    const {
      [this.props.model_name]: {pageLoaded,scrollData},
    } = this.props;
    console.log('pageLoaded',pageLoaded)
    const table=document.querySelector('.ant-table-body')
    if(pageLoaded){
      setTimeout(function () {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      },0)

    }else{
      const {
        [this.props.model_name]: {searchParams},
      } = this.props;
      console.log('searchParams',searchParams)
      dispatch({
        type: `${this.props.model_name}/fetch`,
        payload: searchParams,
        callback:()=>{
          const {dispatch} = this.props;
          dispatch({
            type: `${this.props.model_name}/changeLoaded`,
          })
        }
      });
    }
    const that=this;
    window.addEventListener('resize', this.resize)
    table.addEventListener('scroll', debounce(this.scroll,150))
  }
  scroll=(e)=>{
    const {dispatch} = this.props;
    dispatch({
      type: `${this.props.model_name}/changeScroll`,
      payload: {
        x:e.target.scrollLeft,
        y:e.target.scrollTop
      },
    })
  }
  resize = ()=> {
    this.changeTableY()
  }
  changeTableY=()=>{
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.custom-small-table').getBoundingClientRect().top -50
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)
    const table=document.querySelector('.ant-table-body')
    table.removeEventListener('scroll', debounce(this.scroll,300))
  }
  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: `${this.props.model_name}/fetch`,
      payload: {
        ...values,
      },
      callback: function () {
        console.log('handleSearch callback')
        if (cb) cb()
      }
    });
  }

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
      [this.props.model_name]: {searchParams},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'开始时间'}>
          {getFieldDecorator('started_at', {
            initialValue: moment(searchParams.started_at),
          })(
            <DatePicker
              style={{width:'120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'结束时间'}>
          {getFieldDecorator('ended_at', {
            initialValue: moment(searchParams.ended_at),
          })(
            <DatePicker
              style={{width:'120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'状态'}>
          {getFieldDecorator('status', {
            initialValue: '',
          })(
            <RadioGroup>
              <RadioButton value="">全部</RadioButton>
              <RadioButton value="1">处理中</RadioButton>
              <RadioButton value="-1">失败</RadioButton>
              <RadioButton value="2">成功</RadioButton>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem label="交易编号">
          {getFieldDecorator('trade_no', {
            initialValue: searchParams.trade_no,
          })(<Input    style={{width:'150px'}} placeholder="请输入"/>)}
        </FormItem>
        <FormItem >
          <Button type="primary" icon='search'  onClick={()=> {
            const {form} = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              this.handleSearch({
                page: 1,
                per_page: this.state.per_page,
                ...fieldsValue,
                started_at:  moment(fieldsValue.started_at).format('YYYY-MM-DD'),
                ended_at:  moment(fieldsValue.ended_at).format('YYYY-MM-DD'),
              })

            });
          }}>
            查询
          </Button>
          <Button style={{marginLeft: 8}}  icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        <Button  className="btn-green" icon="export" style={{marginLeft: 8}} type="primary" onClick={
          ()=> {
            this.setState({
              exportModal: true
            })
          }
        }>
          导出EXCEL
        </Button>
        </FormItem>

      </Form>
    );
  }

  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      trade_no:'',
      started_at:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , 'YYYY-MM-DD').format('YYYY-MM-DD'),
      ended_at: moment(new Date(), 'YYYY-MM-DD').format('YYYY-MM-DD'),
      page: 1,
      per_page: 30,
    })
  }
  handleEditStatus=(id,operation_type)=>{
    const that = this;
    this.props.dispatch({
      type: `${this.props.model_name}/edit`,
      payload: {
        id,operation_type
      },
      callback: function () {
        message.success('操作成功')
        const {
          [that.props.model_name]: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  exportCSV = ()=> {
    const that = this;
    const formValues = this.ExportformRef.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const payload = {
      ...formValues,
      started_at: moment(formValues.started_at).format('YYYY-MM-DD'),
      ended_at: moment(formValues.ended_at).format('YYYY-MM-DD'),
    }
    this.props.dispatch({
      type: `${this.props.model_name}/exportCSV`,
      payload: payload,
      callback: function (project_id) {
        console.log('status')
        download(`${config.prefix}/admin/withdrawal_files?project_id=${project_id}&token=${`${sessionStorage.getItem('token')}`}&started_at=${payload.started_at}&ended_at=${payload.ended_at}&name=${payload.name}&trade_no=${payload.trade_no}&status=${payload.status}`)
      }
    });
  }
  render() {
    const {
      [this.props.model_name]: {data, loading, meta,searchParams,selectedRowKeys},
    } = this.props;
    const {
      form: {getFieldDecorator},
    } = this.props;
    const renderMenu = (record) => (
      <Menu onClick={(e)=>this.handleMenuClick(e, record)} selectedKeys={[]}>
        {this.state.user_password_reset && (record.protection_level === 1 || record.protection_level === 3) &&
        <Menu.Item key="reset">重置密码</Menu.Item>}
        {this.state.showdelBtn && record.protection_level !== 2 && <Menu.Item key="delete">删除</Menu.Item>}
      </Menu>
    );
    const columns = [
      {
        title: '分销商头像/昵称',
        dataIndex: 'avatar_url',
        fixed:'left',
        width: 120,
        render:(val,record)=> {
          return <div>
            <img className="table-avatar" src={record.distributor.avatar_url} alt=""/>{ ellipsis(record.distributor.nickname,70)}
          </div>
        }
      },
      {
        title: '提现金额',
        width: 70,
        fixed:'left',
        dataIndex: 'amount',
        render:(val,record)=>{
          return <span className="money">￥{val}元</span>
        }
      },
      {
        title: '账单时间',
        dataIndex: 'created_at',
        width: 150,
        fixed:'left',
        render:(val,record)=>{
          return ellipsis(record.created_at,150)
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 80,
        render(val) {
          let status='',
            statusColor='',
            statusText='';
          switch (val){
            case -1:
              status="close-circle",
                statusColor="#eb2f96",
                statusText='失败';
                  break;
            case 1:
              status="close-circle",
                statusColor="blue",
                statusText='处理中';
              break;
            case 2:
              status="check-circle",
                statusColor="#52c41a",
                statusText='成功';
              break;
          }
          return <Fragment> <Icon type={status} theme="twoTone"  className="table-icon" twoToneColor={statusColor}/>{statusText}</Fragment>
        },
      },
      {
        title: '交易编号',
        width:220,
        dataIndex: 'trade_no',
        render:(val,record)=>{
          return  ellipsis(val,220)
        }
      },
      {
        title: '错误描述',
        dataIndex: 'err_code_des',
        render:(val,record)=>{
          return  ellipsis(val,200)
        }
      },
      {
        title: '操作',
        width: 210,
        fixed:'right',
        render: (val, record, index) =>{
          return    <Fragment>
            {
              record.status===1&&
              <Popconfirm title={'确定要通过该分销商的提现申请吗?'}
                          onConfirm={()=>this.handleEditStatus(record.id,1)}>
              <Button type="primary" icon='check' size="small" onClick={(e)=> {
                e.stopPropagation()
              }
              }>通过审核</Button>
                </Popconfirm>
            }
            {
              record.status===1&&
              <Popconfirm title={'确定要取消该分销商的提现申请吗?'}
                          onConfirm={()=>this.handleEditStatus(record.id,2)}>
              <Button type="danger" icon='close' size="small" onClick={(e)=> {
                e.stopPropagation()
              }
              }>取消审核</Button></Popconfirm>
            }
          </Fragment>
        }
      },
    ];
    const rowSelection = {
      columnWidth:40,
      selectedRowKeys,
      columnTitle:' ',
      onChange:(selectedRowKeys) => {
        this.props.dispatch({
          type: `${this.props.model_name}/changeSelectRow`,
          payload: selectedRowKeys,
        })
      },
    };

    return <div className="custom-card">
      <div className="table-title" >提现审核</div>
      <div className="table-page">
          <div className="table-condition">{this.renderSimpleForm()}</div>
          <Table
            style={{color: '#fff'}}
            className="custom-small-table"
            loading={loading}
            rowKey={'id'}
            dataSource={data}
            columns={columns}
            pagination={false}
            size="small"
            scroll={{x: 1100, y: this.state.tableY}}
            rowSelection={rowSelection}
            onRow={(record) => ({
              onClick: () => {
                this.props.dispatch({
                  type:`${this.props.model_name}/selectRow`,
                  payload: record,
                })
              },
            })}
          />

      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{...searchParams}} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={''}
        destroyOnClose
        visible={this.state.editModal}
        centered
        footer={null}
        width={600}
        onCancel={()=> {
          this.setState({editModal: false})
        }}
      >
        <DetailInfo {...this.state.editRecord}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.exportModal}  modalClass={'exportModal'}  title={'导出提现EXCEL'} />}
        visible={this.state.exportModal}
        className={'exportModal'}
        centered
        onCancel={()=> {
          this.setState({exportModal: false})
        }}
        onOk={this.exportCSV}
      >
        <ExportForm banks={this.state.banks}  wrappedComponentRef={(inst) => this.ExportformRef = inst}/>

      </Modal>
    </div>
  }
}

export default BasicList;
